<template>
  <div ref="chartRef" style="width: 100%; height: 400px;"></div>
</template>

<script>
import { ref, onMounted, onUnmounted, watch } from 'vue';
import * as echarts from 'echarts';

export default {
  name: 'PieChart',
  props: {
    pieData: {
      type: Object,
      default: () => ({})
    }
  },
  setup(props) {
    const chartRef = ref(null);
    const chartInstance = ref(null);

    const initChart = () => {
      if (!chartRef.value) return;

      // 如果已经初始化，销毁旧实例
      if (chartInstance.value) {
        chartInstance.value.dispose();
      }

      chartInstance.value = echarts.init(chartRef.value);

      // 将数据转换为 ECharts 需要的格式
      const pieData = [
        { value: props.pieData.positive, name: '正向' },
        { value: props.pieData.neutral, name: '中性' },
        { value: props.pieData.negative, name: '负向' }
      ];

      const option = {
        title: {
          text: '情感分类',
          left: 'center'
        },
        tooltip: {
          trigger: 'item'
        },
        legend: {
          orient: 'vertical',
          left: 'left'
        },
        series: [
          {
            name: '情感',
            type: 'pie',
            radius: '50%',
            data: pieData,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      };

      chartInstance.value.setOption(option);
    };

    const resizeChart = () => {
      if (chartInstance.value) {
        chartInstance.value.resize();
      }
    };

    onMounted(() => {
      initChart();
      window.addEventListener('resize', resizeChart);
    });

    onUnmounted(() => {
      window.removeEventListener('resize', resizeChart);
      if (chartInstance.value) {
        chartInstance.value.dispose();
      }
    });

    // 监听 pieData 的变化，重新初始化图表
    watch(() => props.pieData, () => {
      initChart();
    });

    return {
      chartRef
    };
  }
};
</script>

<style scoped>
/* 可以根据需要添加样式 */
</style>